package com.app.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.app.model.AdminUserModel;
import com.app.model.CategoryModel;
import com.app.service.AdminUserService;
import com.app.service.CategoryService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

@RestController
@Controller
@RequestMapping("/admin/data")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired

    private AdminUserService adminUserService;

    @GetMapping("/getPerTree")//公共数据管理树
    public Result<Object> getPerTree(
            @RequestParam("name") String name,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<CategoryModel> catModelList = categoryService.selectPerTree(name);//全查
        if (catModelList == null) {
            return Result.error(200, "暂无数据");
        }
        List<Integer> arr1 = new ArrayList<>();
        for (int i = 0; i < catModelList.size(); i++) {
            arr1.add(catModelList.get(i).getId());
        }
        Integer ArrId = 1;
        boolean result1 = arr1.contains(ArrId);
        List<Integer> pidArr1 = new ArrayList<>();
        if (!result1) {
            for (int i = 0; i < catModelList.size(); i++) {

                boolean PidResult = arr1.contains(catModelList.get(i).getPid());
                if (!PidResult) {
                    pidArr1.add(catModelList.get(i).getPid());
                }
            }
            pidArr1.add(ArrId);
            arr1.addAll(pidArr1);
            LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(arr1);
            ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet);
            List<CategoryModel> catModelList1 = new ArrayList<>();
            for (int i = 0; i < listWithoutDuplicates.size(); i++) {
                CategoryModel categoryModel = categoryService.getCategoryById(listWithoutDuplicates.get(i));
                catModelList1.add(categoryModel);
            }
            return Result.success(findChildren(catModelList1, 0));
        }
        return Result.success(findChildren(catModelList, 0));
    }

    private List<CategoryModel> findChildren(List<CategoryModel> modelList, Integer pid) {
        List<CategoryModel> personModelList = new ArrayList<>();
        for (int i = 0; i < modelList.size(); i++) {
            if (modelList.get(i).getPid() == pid) {
                CategoryModel model = modelList.get(i);
                List<CategoryModel> modelList1 = findChildren(modelList, model.getId());
                for (int j = 0; j < modelList1.size(); j++) {
                    if (modelList1 != null && modelList1.size() > 0) {
                        model.setChild(modelList1);
                    }
                }
                personModelList.add(model);
            }
        }
        return personModelList;
    }

    @GetMapping("/getCategoryList")//数据管理分页查询
    public Result<Object> getCategoryList(
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            @RequestParam(required = false) String name,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        Page<CategoryModel> categoryModelPage = categoryService.categoryPageList(page, limit, name);
        if (categoryModelPage == null) {
            return Result.error(200, "暂无数据");
        }
        int count = (int) categoryModelPage.getTotal();
        List<CategoryModel> categoryModelList;
        categoryModelList = categoryModelPage.getRecords();
        CategoryVo vo = new CategoryVo();
        vo.setList(categoryModelList);
        vo.setCount(count);
        return Result.success(vo);
    }

    @PostMapping("/insertAndUpdateCategory")//    新增/修改数据管理
    public Result<Object> insertRole(
            @RequestBody JSONObject json,
            HttpServletRequest request) {
        Integer id = Integer.valueOf(json.get("id").toString());
        String name = json.get("name").toString();
        Integer pid = Integer.valueOf(json.get("pid").toString());
        Integer sort = Integer.valueOf(json.get("sort").toString());
        Integer status = Integer.valueOf(json.get("status").toString());

        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryModel model = new CategoryModel();
        model.setId(id);
        model.setPid(pid);
        model.setName(name);
        model.setSort(sort);
        model.setStatus(status);
        try {
            if (id > 0) {
                model.setId(id);
                model.setUpdateTime(CommonHelp.getNowTimestamp());
                categoryService.update(model);
            } else {
                model.setCreateTime(CommonHelp.getNowTimestamp());
                categoryService.insert(model);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success(null);
    }

    @GetMapping("/updateCategoryStatus")//修改状态
    public Result<Object> updateStatus(
            @RequestParam("id") Integer id,
            @RequestParam("status") Integer status,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryModel model = new CategoryModel();
        model.setId(id);
        model.setStatus(status);
        categoryService.update(model);
        return Result.success(null);
    }

    @GetMapping("/deleteById")//删除数据
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryModel model = categoryService.getCategoryById(id);
        if (model == null) {
            return Result.error(500, "该条数据不存在");
        } else {
            categoryService.delete(id);
            return Result.success(null);
        }
    }

    @GetMapping("/selectCategoryByName")
    public Result<Object> selectCategoryByName(String name, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryModel model = categoryService.getCategoryByName(name);
        if (model == null) {
            return Result.error(500, "该条数据不存在");
        } else {
            CategoryVo vo = new CategoryVo();
            List<CategoryModel> categoryModelList = categoryService.getCategoryByPid(model.getId());
            vo.setList(categoryModelList);
            return Result.success(vo);
        }
    }
}
